import requests
from bs4 import BeautifulSoup
import pandas as pd

def scrape_douban():
    url = "https://movie.douban.com/top250"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

    movies = []
    for item in soup.find_all('div', class_='item'):
        title = item.find('span', class_='title').text
        rating = item.find('span', class_='rating_num').text
        movies.append({"title": title, "rating": rating})

    df = pd.DataFrame(movies)
    df.to_csv('data/douban_top250.csv', index=False)
    print("数据已保存到 data/douban_top250.csv")

if __name__ == "__main__":
    scrape_douban()